#include "misc_log.h"
#include "version.h"
#include "global.h"
#include "task_misc.h"

#include "service/include/swei_config.h"

#include "utils/utils_timer.h"
#include "misc/misc_print.h"
#include "hal_adapter.h"

/**
 * @brief 设备运行状态
 */
extern device_status_t dev_sta;

/*
 *   @brief  获取MCU复位类型标记
 *   @param  none.
 *   @retval MCU reset type.
 */
static mcu_rst_t hdl_mcu_reset_type_get(void)
{
	mcu_rst_t type = 0;
	unsigned int reg = RCC->CSR;

    log_i("RCC->CSR: 0x%08X\r\n", reg);

    if (reg & 0x80000000)
        type |= MCU_RST_LPWR;
    if ((reg & 0x40000000) || (reg & 0x20000000))
        type |= MCU_RST_WDG;
    if (reg & 0x10000000)
        type |= MCU_RST_SFT;
    if (reg & 0x08000000) {
        type |= MCU_RST_POR;
    }
    if (reg & 0x04000000)
        type |= MCU_RST_PIN;
    if (reg & 0x02000000) {
        type |= MCU_RST_OBL;
    }

    return type;
}

/**
 * @brief Get the mcu reset type str object
 * @param  type             My Param doc
 * @return const char* 
 */
static const char *get_mcu_reset_type_str(mcu_rst_t type)
{
	static char str[32] = {0};

	str[0] = 0;
    if (type & MCU_RST_LPWR)
        strcat(str, "PWR,");
    if (type & MCU_RST_WDG)
        strcat(str, "WDG,");
    if (type & MCU_RST_SFT)
        strcat(str, "SFT,");
    if (type & MCU_RST_POR)
        strcat(str, "POR,");
    if (type & MCU_RST_PIN)
        strcat(str, "PIN,");
    if (type & MCU_RST_OBL)
        strcat(str, "OBL,");
    
    return str;
}

/**
 * @brief clear the mcu reset type
 */
static void hdl_mcu_reset_type_clear(void)
{
    set_bit(RCC->CSR, 23);
}

/**
 \t@brief 显示开机信息
 */
void show_poweron_info(void)
{
    uint8_t pwr_type = hdl_mcu_reset_type_get();
    log_i("\t**************** PowerOn Info *******************\r\n");
    log_i("\t 1. Reset Code   : 0x%02X\r\n", pwr_type);
    log_i("\t 2. Reset Reason : %s\r\n", get_mcu_reset_type_str(pwr_type));
    log_i("\t 3. Fota Flag    : %s\r\n", dev_sta.mcu.fota_mark);
    log_i("\t*************************************************\r\n");
    hdl_mcu_reset_type_clear();
}

